package com.security.security;


import com.security.security.filter.JWTAuthenticationFilter;
import com.security.security.filter.JWTAuthorizationFilter;
import com.security.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

/**
 * @author zhuchao
 * @create 2021-03-29 12:20
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

	@Autowired
	private IUserService userService;

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(userService);
	}

	/**
	 * 需要放行的URL
	 */
	private static final String[] AUTH_WHITELIST = {
			"/web/order/paymentOrderPull",//订单拉取
	};

	/**
	 * 安全配置
	 */
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// 跨域共享
		http.cors()
				.and()
				// 跨域伪造请求限制无效
				.csrf().disable()
				.authorizeRequests()
				// 访问/data需要ADMIN角色
//				.antMatchers("/data").hasRole("ADMIN")
				.antMatchers(AUTH_WHITELIST).permitAll()
				// 其余资源任何人都可访问
				.anyRequest().permitAll()
				.and()
				// 添加JWT登录拦截器
				.addFilter(new JWTAuthenticationFilter(authenticationManager()))
				// 添加JWT鉴权拦截器
				.addFilter(new JWTAuthorizationFilter(authenticationManager()))
				.sessionManagement()
				// 设置Session的创建策略为：Spring Security永不创建HttpSession 不使用HttpSession来获取SecurityContext
				.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
				.and()
				// 异常处理
				.exceptionHandling()
				// 匿名用户访问无权限资源时的异常
				.authenticationEntryPoint(new JWTAuthenticationEntryPoint());
	}

	/**
	 * 跨域配置
	 * @return 基于URL的跨域配置信息
	 */
	@Bean
	CorsConfigurationSource corsConfigurationSource() {
		final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		// 注册跨域配置
		source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
		return source;
	}
}